//
//  XMPPManager.swift
//  edu
//
//  Created by karlzhou on 15/12/24.
//  Copyright © 2015年 karlzhou. All rights reserved.
//

import UIKit

class XMPPManager: NSObject,XMPPStreamDelegate {

    private  let hostname:String="172.18.1.133"
    private  let port:UInt16=5222
    private static var manager:XMPPManager?
    private var xmppStream:XMPPStream?
    static func shareManager() -> XMPPManager{
        if manager == nil {
            manager=XMPPManager()
        }
        return manager!
    }
    override init() {
        
    }
    private func setupXmppStream(delegate:XMPPStreamDelegate){
        if (self.xmppStream == nil) {
            xmppStream = XMPPStream()
            xmppStream?.addDelegate(delegate, delegateQueue: dispatch_get_main_queue())
            
        }
    }
    func login(username:String,password:String,delegate:XMPPStreamDelegate){
       
        if(password.isEmpty || username.isEmpty){
            print("can not be null")
        }else{
            self.setupXmppStream(delegate)
           
            let isConnected:Bool=(self.xmppStream?.isConnected())!
            if !isConnected {
                xmppStream?.hostName=self.hostname
                xmppStream?.hostPort=self.port
                let jid = XMPPJID.jidWithUser(username, domain: "master", resource: "Ework")
                self.xmppStream?.myJID=jid
                var error:()
                do{
                    
                   try  error = (self.xmppStream?.connectWithTimeout(60))!
                   
                } catch{
                    print("connect error:\(error)")
                }
                
            }
        }
    }
    
}
